<template>
  <div v-if="infoData.mobile">
    <div class="header">
      <dl>
        <dd><img src="../../assets/dimg/d_person_logo.png" alt="" /></dd>
        <dt>
          <h1>{{ infoData.mobile | mobil }}</h1>
          <p>推荐码：{{ infoData.recode }}</p>
        </dt>
      </dl>
    </div>
    <div class="gray"></div>
    <div class="btm">
      <ul>
        <li @click="ShouPup">
          <span>性别</span>
          <img src="../../assets/img/gg_icon_right.png" alt="" />
          <i>{{ sex }}</i>
          <a></a>
        </li>
        <li @click="openPicker">
          <span>生日</span>
          <img src="../../assets/img/gg_icon_right.png" alt="" />
          <i v-if="birthtime != ''">{{ birthtime }}</i>
          <i v-if="birthtime == ''">请选择生日</i>
          <a></a>
        </li>
        <li @click="openAreaPopup" style="border: 0;">
          <span>地区</span>
          <img src="../../assets/img/gg_icon_right.png" alt="" />
          <i v-show="cityName !== 0">{{ cityName }}</i>
          <a v-show="cityName === 0">设置所在地区</a>
        </li>
        <div class="gray" style="margin-left: -0.4rem;"></div>
        <li @click="$router.push('/about')" style="border: 0">
          <span>关于我们</span>
          <img src="../../assets/img/gg_icon_right.png" alt="" />
        </li>
        <div class="gray" style="margin-left: -0.4rem;"></div>
        <!--                <li class="last" style="border: 0;" @click="logout()">退出登录</li>-->
      </ul>
    </div>
    <!--性别选择-->
    <mt-popup v-model="popupVisible" closeOnClickModal="true" position="bottom">
      <mt-picker
        :slots="slots"
        @change="onValuesChange"
        style="width: 7.5rem;"
        showToolbar
      >
        <div class="picker-toolbar-title">
          <div class="usi-btn-cancel" @click="popupVisible = !popupVisible">
            取消
          </div>
          <div class="">性别选择</div>
          <div class="usi-btn-sure" @click="sexOcheck()">确定</div>
        </div>
      </mt-picker>
    </mt-popup>
    <!--日期选择-->
    <div @touchmove.prevent>
      <mt-datetime-picker
        ref="pickertime"
        v-model="popupVisibletime"
        type="date"
        :startDate="startDate"
        year-format="{value} 年"
        month-format="{value} 月"
        date-format="{value} 日"
        @confirm="timpicker"
      >
      </mt-datetime-picker>
    </div>
    <!--地区选择-->
    <mt-popup v-model="areaVisible" position="bottom" style="width: 100%;">
      <mt-picker
        :slots="areaList"
        value-Key="name"
        :show-toolbar="true"
        @change="selectArea"
      >
        <div class="picker-toolbar-title">
          <div class="usi-btn-cancel" @click="closePopup">取消</div>
          <div class="">地区选择</div>
          <div class="usi-btn-sure" @click="sureArea">确定</div>
        </div>
      </mt-picker>
    </mt-popup>
  </div>
</template>

<script>
import { axiosPost, axiosPostnotoken } from '../../axios';
import { Toast } from 'mint-ui';

export default {
  name: '',
  data() {
    return {
      infoData: {},
      showToolbar: true,
      sex: '',
      sexId: '',
      slots: [
        {
          values: ['请选择性别', '男', '女'],
        },
      ],
      popupVisible: false,
      popupVisibletime: '',
      birthtime: '',

      handler: function(e) {
        e.preventDefault();
      }, //阻止body滑动
      areaList: [
        {
          //一级   省
          flex: 1,
          values: ['请选择'],
          className: 'slot1',
          textAlign: 'center',
        },
        {
          divider: true,
          content: '-',
          className: 'slot1',
        },
        {
          //二级   市
          flex: 1,
          values: ['请选择'],
          className: 'slot1',
          textAlign: 'center',
        },
      ],
      flag: false, //初始时禁止picker自动加载
      areaVisible: false, //初始选择地区弹窗为关闭状态
      cityName: 0, //最终选中的地区的名字
      cityId: [0, 0],

      provincelist: [],
      provincechecklist: [],
      citylist: [],
      citychecklist: [],
      startDate: new Date('1950-01-01'),
    };
  },
  watch: {
    areaVisible: {
      handler(val) {
        if (val) {
          document.getElementsByTagName('body')[0].style.overflow = 'hidden';
        } else {
          document.getElementsByTagName('body')[0].style.overflow = 'auto';
        }
      },
    },
  },
  mounted() {
    //省份信息获取
    axiosPostnotoken('index/province', {}, (response) => {
      this.provincelist = [];
      this.provincechecklist = [];
      for (let i in response.data) {
        let item = response.data[i];
        this.provincelist.push(item);
        this.provincechecklist[item] = i;
      }
      this.areaList[0].values = this.provincelist;
    });

    this.getuserinfo();
  },
  methods: {
    //性别选择提交
    sexOcheck() {
      this.popupVisible = !this.popupVisible;
      //console.log(this.sex)
      let sexData = '';
      switch (this.sex) {
        case '男':
          sexData = 1;
          break;
        case '女':
          sexData = 2;
          break;
        default:
          sexData = 0;
          break;
      }
      this.sexId = sexData;
      axiosPost(
        'users/add_user_info',
        {
          sex: sexData,
          birthday: this.birthtime,
          province_id: this.cityId[0],
          city_id: this.cityId[1],
        },
        (res) => {
          //console.log(res)
          if (res.code !== 1) {
            return Toast(res.msg);
          }
        }
      );
    },
    //获取用户信息
    getuserinfo() {
      if (!localStorage.getItem('userinfo')) {
        return;
      }
      axiosPost(
        'users/user_info',
        {
          user_id: JSON.parse(localStorage.getItem('userinfo')).user_id,
        },
        (res) => {
          //console.log(res)
          if (res.code !== 1) {
            return Toast(res.msg);
          }
          this.infoData = res.data;
          sessionStorage.usersesion = JSON.stringify(res.data);

          this.$nextTick(() => {
            //性别
            this.sexId = res.data.sex;
            switch (res.data.sex) {
              case 1:
                this.sex = '男';
                break;
              case 2:
                this.sex = '女';
                break;
              default:
                this.sex = '请选择性别';
                break;
            }
            //生日
            if (res.data.birthday) {
              this.birthtime = res.data.birthday;
            }
            //省份与城市
            if (res.data.province_name && res.data.province_id !== 0) {
              this.cityName =
                res.data.province_name + '-' + res.data.province_name;
              this.cityId = [res.data.province_id, res.data.city_id];
            }
          });
        }
      );
    },
    ShouPup() {
      this.popupVisible = true;
    },
    onValuesChange(picker, values) {
      this.sex = values[0];
      if (values[0] > values[1]) {
        picker.setSlotValue(1, values[0]);
      }
    },
    openPicker() {
      this.popupVisibletime = new Date(this.birthtime);
      this.$refs.pickertime.open();
    },

    timpicker(val) {
      let date = new Date(val);
      let Y = date.getFullYear() + '-';
      let M =
        (date.getMonth() + 1 < 10
          ? '0' + (date.getMonth() + 1)
          : date.getMonth() + 1) + '-';
      let D =
        (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '';
      this.birthtime = Y + M + D;
      axiosPost(
        'users/add_user_info',
        {
          sex: this.sexId,
          birthday: this.birthtime,
          province_id: this.cityId[0],
          city_id: this.cityId[1],
        },
        (res) => {
          //console.log(res)
          if (res.code !== 1) {
            return Toast(res.msg);
          }
        }
      );
    },
    // 打开选择地区的弹窗
    openAreaPopup() {
      let that = this;
      that.areaVisible = true;
      that.flag = true;
    },
    // 选择地区
    selectArea(picker, values) {
      let that = this;
      if (that.flag) {
        that.area(that.provincechecklist[values[0]]).then(function() {
          //通过 二级 市的id  获取区域的列表
          picker.setSlotValues(1, that.citylist); //将区的地区列表放入 areaList的三级列表中
        });
        let arr = picker.getValues();
        that.cityId = [
          that.provincechecklist[arr[0]],
          that.citychecklist[arr[1]],
        ];
        that.cityName = `${arr[0]}-${arr[1]}`;
      }
    },
    area(id) {
      let that = this;
      //因为我们需要拿到axios请求的数据，来进行下一个axios的请求，
      //所以我们这里使用promise对象，将异步转换为同步。
      let promise = new Promise(function(resolve) {
        axiosPostnotoken(
          'index/city',
          {
            province_id: id,
          },
          (response) => {
            that.citylist = [];
            that.citychecklist = [];
            for (let i in response.data) {
              let item = response.data[i];
              that.citylist.push(item);
              that.citychecklist[item] = i;
            }
            resolve(that.citylist);
          }
        );
      });
      return promise;
    },
    //关闭弹窗
    closePopup() {
      let that = this;
      that.areaVisible = false;
    },
    //确定地区
    sureArea() {
      let that = this;
      that.areaValue = that.cityName;
      that.areaVisible = false;
      axiosPost(
        'users/add_user_info',
        {
          sex: this.sexId,
          birthday: this.birthtime,
          province_id: this.cityId[0],
          city_id: this.cityId[1],
        },
        (res) => {
          //console.log(res)
          if (res.code !== 1) {
            return Toast(res.msg);
          }
        }
      );
    },
    /*解决iphone页面层级相互影响滑动的问题*/
    closeTouch: function() {
      document
        .getElementsByTagName('body')[0]
        .addEventListener('touchmove', this.handler, { passive: false }); //阻止默认事件
      //console.log("closeTouch haved happened.");
    },
    openTouch: function() {
      document
        .getElementsByTagName('body')[0]
        .removeEventListener('touchmove', this.handler, { passive: false }); //打开默认事件
      //console.log("openTouch haved happened.");
    },
    //退出登录
    logout() {
      axiosPost('users/logout', {}, (res) => {
        //console.log(res)
        if (res.code !== 1) {
          return Toast(res.msg);
        }
        Toast({
          message: '已退出登录，返回首页',
          duration: 1000,
        });
        localStorage.removeItem('userinfo');
        this.$router.push('/index');
      });
    },
  },
};
</script>

<style scoped lang="less">
@import '../../style/default';

.picker-toolbar-title {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  height: 40px;
  line-height: 40px;
  font-size: 16px;
}

.usi-btn-cancel,
.usi-btn-sure {
  color: @color1;
}

.header {
  overflow: hidden;
  background: @color4;

  dl {
    margin-top: 0.4rem;
    height: 1.4rem;
    padding: 0 0.4rem;

    dd {
      float: left;
      width: 1.2rem;
      height: 1.2rem;
      border-radius: 0.6rem;

      img {
        width: 100%;
      }
    }

    dt {
      float: left;
      width: 5.5rem;
      min-height: 1.6rem;

      h1 {
        font-size: 0.41rem;
        font-weight: 400;
        color: @color6;
        padding-left: 0.24rem;
        margin-top: 0.18rem;
      }

      p {
        font-size: @font26;
        font-weight: 400;
        color: @color6;
        line-height: 0.4rem;
        padding-left: 0.24rem;
      }
    }
  }
}

.btm {
  background: @color4;

  ul {
    padding-left: 0.4rem;

    .last {
      font-size: @font32;
      color: @color2;
      text-align: center;
    }

    li {
      height: 1.1rem;
      line-height: 1.1rem;
      border-bottom: 1px solid #efefef7a;

      span {
        font-size: @font28;
        color: @color5;
        font-family: PingFang SC;
      }

      a {
        font-size: @font24;
        color: @color1;
        float: right;
        margin-right: 0.1rem;
      }

      i {
        font-size: @font24;
        color: @color2;
        float: right;
        margin-right: 0.1rem;
      }

      img {
        display: inline-block;
        width: 0.15rem;
        float: right;
        margin-top: 0.42rem;
        margin-right: 0.4rem;
      }
    }
  }
}
</style>
